//
//  GNOAuthViewController.swift
//  SinaWeChat
//
//  Created by mac on 15/12/7.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import SVProgressHUD


//添加一个webView
//打开登陆界面

//登录需要一个常量

let WB_APPKEY = "2397977184"
let WB_APP_SECRET = "51de2a7c2644183518014b690c125137"
let WB_REDIRECT_URI = "https://www.baidu.com/"



class GNOAuthViewController: UIViewController,UIWebViewDelegate {
    
    
    private lazy var webView = UIWebView()
    
    override func loadView() {
        
        webView.delegate = self
        
        view = webView
    }
    override func viewDidLoad() {
        super.viewDidLoad()

       //定义 url
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APPKEY)&redirect_uri=\(WB_REDIRECT_URI)"
        
        let url = NSURL(string: urlString)!
        
        //定义 request
        let request = NSURLRequest(URL: url)
        
        webView.loadRequest(request)
        
        setupUI()
    }
    
    
    private func setupUI(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem( title: "取消", target: self, action: "dismiss")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem( title: "自动填充", target: self, action: "autoFill")
        
        navigationItem.title = "微博登录"
    }
    
    
    
    //MARK : -获取acceToken
    //此处原有的网络请求的方法已经抽取到ViewModel
    
   
    
    //MARK:-监听方法
    
    @objc private func dismiss(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoFill(){
        print("autoFill")
        
        //了解 javaScript
        let jsString = "document.getElementById('userId').value='yohtr35601@163.com';document.getElementById('passwd').value='qw1987'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
}


extension  GNOAuthViewController{
    
    
    //MARK : -webViewDelegate
    
    //webView将要去加载某个 请求的时候,会调用这个方法,判断是否要加载
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //拦截回调页:如果是回调页,那么在回调地址里面截取 code,然后拿着 code 去获取 accessToken
        guard let url = request.URL?.absoluteString else{
            return true
        }
        
        //如果判断不是以回调页开头,就放行让其去加载
        if !url.hasPrefix(WB_REDIRECT_URI){
            
            return true
        }
        
        //执行到这个地方,就代表是回调页
        
        
        
        if request.URL!.query!.hasPrefix("code="){
            
            //获取code
            print(request.URL?.query)
            //截取授权code
            let code = request.URL!.query!.substringFromIndex("code=".endIndex)
            //获取accessToken
            
            
            
            GNUserAccountViewModel.sharedAccount.loadAccessToken(code, complete: { (isSuccessed) -> () in
                if !isSuccessed {
                    print("加载失败")
                    SVProgressHUD.showErrorWithStatus("网络异常,登录失败")
                    return
                }
                
                print("加载成功")
                
                SVProgressHUD.dismiss()
                
                //1.关闭当前页面. 页面并不立即关闭,我们需要在直接关闭完页面之后再去切换界面
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    // 2.跳到欢迎页
                    // 切换根控制器的逻辑,应该放在一起,一般放在 appdelegate 里面
                    NSNotificationCenter.defaultCenter().postNotificationName(GNSwitchRootVCNotifation, object: self)
                    
                })
                
            })
            //loadAccessToken(code)
        }else{
            
            print(request.URL)
            //见当前页面给干掉
            dismiss()
        }
        
        
        
        
        
        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }

    
    
}